<!-- 客户服务 -->
<template>
  <div class="customer-service-wp">
  	<div class="left">
  		<div class="online">
  			<div class="title">
  				<svg-icon name="now-chat" style="position: relative; top: 2px;"></svg-icon>
  				<span>会话中</span>
  			</div>
  			<div class="list">
  				<!-- <div class="item active">
  					<div class="num">23</div>
  					<div class="name">张三</div>
  					<div class="bt">
  						<div class="text">哈利波特这是一个什么样的人？</div>
  						<div class="time">11:39</div>
  					</div>
  				</div> -->
  				<div v-for="(item, index) in chatStore.online" :key="index" class="item"
  					:class="{active: item.id == chatStore.chatId}"
  					@click="setChatCurrent(item)">
  					<!-- <div class="num">23</div> -->
  					<div class="name">{{item.name}}</div>
  					<!-- <div class="bt">
  						<div class="text">哈利波特这是一个什么样的人？</div>
  						<div class="time">11:39</div>
  					</div> -->
  				</div>
  			</div>
  		</div>
  		<div class="history">
  			<div class="title">历史会话</div>
  			<div class="list">
  				<div v-for="(item, index) in chatStore.offline" :key="index" class="item"
  					:class="{active: item.id == chatStore.chatId}"
  					@click="setChatCurrent(item)">
  					<div class="name">{{item.name}}</div>
  				</div>
  			</div>
  		</div>
  	</div>
  	<div class="right">
  		<div class="msg-box" ref="msgboxRef">
  			<div v-for="(item, index) in chatMessage" :key="index" 
  				class="msg-item"
  				:class="{me: item.type == 1}"
  				:style="{
  					opacity: _d.opacity
  				}">
  				<!-- <img class="user-img" 
  					:src="item.type == 1 ? '/static/image/user2.png' : '/static/image/user1.png'"/> -->
  				<div class="user-img">
  					{{item.type == 1 ? 'ME' : (item.name?.slice(0, 2) || '')}}
  				</div>
  				<div>
  					<div class="name">{{item.name}}</div>
  					<div class="msg-group">
  						<MsgText v-if="item.msg.type == 'TEXT'" :data="item.msg.value"></MsgText>
  						<MsgImage v-if="item.msg.type == 'IMAGE'" :data="item.msg.value"></MsgImage>
  						<MsgVideo v-if="item.msg.type == 'VIDEO'" :data="item.msg.value"></MsgVideo>
  					</div>
  					<div class="time">{{item.time}}</div>
  				</div>
  			</div>
  		</div>
  		<div class="handle-box">
  			<div class="send-choice">
  				<!-- <svg-icon class="icon" name="face"></svg-icon> -->
  				<svg-icon class="icon" name="image" @click="showFile('IMAGE')"></svg-icon>
  				<svg-icon class="icon" name="vedio" @click="showFile('VIDEO')"></svg-icon>
  			</div>
  			<div v-if="!isHistory" class="ipt-box">
  				<el-input class="ipt" v-model="_d.msgText" type="textarea" resize="none" @keyup.enter="sendText()"></el-input>
  			</div>
  			<div class="btn-box">
  				<div>
  					<el-button type="primary" @click="showRecord()">新建工单</el-button>
  					<!-- <el-button v-if="!isHistory" type="primary">结束会话</el-button> -->
  				</div>
  				<el-button v-if="!isHistory" type="primary" @click="sendText()">发送</el-button>
  			</div>
  		</div>
  	</div>

  	<input v-show="false" ref="fileRef" type="file" :accept="_d.file.accept" @change="fileChange"/>
  </div>
</template>

<script setup>
	import { reactive, ref, computed, onMounted } from 'vue'
	import {useRouter} from "vue-router";
	import {ElNotification} from "element-plus"
	import MsgText from "./modules/MsgText.vue";
	import MsgImage from "./modules/MsgImage.vue";
	import MsgVideo from "./modules/MsgVideo.vue";
	import {Session} from "/@/utils/storage.ts";
	import {useUserInfo} from "/@/stores/userInfo.ts";
	import {useChatStore} from "/@/stores/chatStore.js";
	import dayjs from "dayjs";
	import {formatMessage} from "/@/utils/Tools.js";

	const router = useRouter();
	const chatStore = useChatStore();

	const msgboxRef = ref();
	const fileRef = ref();

	const _d = reactive({
		opacity: 0, // 显示隐藏
		msgText: '',

		// 文件
		file: {
			type: '', // 类型
			accept: '', // 数据类型
			errorMsg: '', // 错误消息
		}

	})

	const nowChat = computed(() => {
		return chatStore.online[chatStore.chatIndex];
	})

	const chatMessage = computed(() => {
		let res = chatStore.chatMessage;
		if(res.length) {
			setTimeout(() => {
				setScrollBottom();
			}, 200);
		}
		return res;
	})

	// 当前是会话中，还是历史会话
	const isHistory = computed(() => {
		return !!chatStore.offline.find(item => item.id == chatStore.chatId);
	})

	onMounted(async () => {

		// 上线
		chatStore.beOnline();

		// 获取所有聊天人列表
		await chatStore.getChatList();
	
		// 获取第一个聊天消息
		await chatStore.getChatMessage();

	})

	// 设置当前的聊天人
	function setChatCurrent(item) {
		_d.opacity = 0;
		chatStore.getChatMessage(item.id);
	}

	// 发送文本
	function sendText() {
		// 发送消息
		sendMessage('TEXT', _d.msgText);
	}

	// 发送消息
	async function sendMessage(type, msg) {
		if(!chatStore.online.length) {
			ElNotification.error({
				title: '提示',
				messages: '当前没有聊天对象'
			})
			return;
		}
		let userInfo = useUserInfo().userInfos;
		let params = {
			userId: userInfo.userId,
			targetUserId: chatStore.chatId,
			message: JSON.stringify({
				type: type,
				value: msg
			})
		}
		await chatStore.sendChatMessage(params);
		_d.msgText = '';
		chatStore.chatMessage.push({
			type: 1, // 1我，2客户
			name: userInfo.realName,
			msg: formatMessage(params.message),
			time: dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss')
		})
	}

	// 设置滚动到底部
	function setScrollBottom() {
		let height = msgboxRef.value.scrollHeight;
		msgboxRef.value.scrollTop = height;
		_d.opacity = 1;
	}

	// 新建工单
	function showRecord() {
		Session.set('workOrderShowId', -1);
		router.push({
			path: '/workOrder/index'
		})
	}

	// 显示文件
	function showFile(type) {
		_d.file.type = type;
		if(type == 'IMAGE') {
			_d.file.accept = 'image/jpeg,image/png';
		} else if(type == 'VIDEO') {
			_d.file.accept = 'audio/mp4,video/mp4,application/ogg,audio/ogg,wideo/ogg,video/webm';
		}
		setTimeout(() => {
			fileRef.value.click();
		}, 100);
	}

	// 文件改变
	function fileChange(e) {
		let files = e.target.files;
		if(!files.length) {
			return;
		}
		let file = e.target.files[0];
		const reader = new FileReader();
		reader.readAsBinaryString(file);     // 注意：读取到的是二进制字符串
		reader.onload = function(e){
			let fileText = e.target.result;  // 二进制字符串文本
			fileText = window.btoa(fileText);  // 注意：是使用btoa对"二进制字符串"进行Base64编码
			if(_d.file.type == 'IMAGE') { // 图片处理
				fileText = 'data:image/png;base64,'+fileText;
			} else if (_d.file.type == 'VIDEO') { // 视频处理
				fileText = 'data:video/mp4;base64,'+fileText;
			}
			// 发送消息
			sendMessage(_d.file.type, fileText);
		}
	}

</script>

<style lang="scss" scoped>
.customer-service-wp {
	display: flex;
	flex-direction: row !important;
	border: 1px solid #d7d7d7;
	.left {
		width: 200px;
		border-right: 1px solid #d7d7d7;
		height: 100%;
		& > div {
			display: flex;
			flex-direction: column;
		}
		& > div > .title {
			background: var(--blue-color);
			height: 36px;
			color: #fff;
			display: flex;
			align-items: center;
			justify-content: center;
			gap: 10px;
			font-size: 16px;
		}
		& > div > .list { 
			height: 0;
			flex: 1;
			overflow: scroll;
			padding: 10px 0;
		}
		.online {
			height: 70%;
		}
		.history {
			height: 30%;
			border-top: 1px solid #d7d7d7;
		}
		.item {
			position: relative;
			margin-bottom: 5px;
			padding: 5px 10px;
			cursor: pointer;
			background: rgba(0,0,0,0.03);
			&:hover, &.active {
				color: #409EFF;
			}
			.num {
				position: absolute;
				top: 5px;
				right: 10px;
				background: #DE2910;
				height: 18px;
				line-height: 18px;
				font-size: 12px;
				border-radius: 9px;
				padding: 0 5px;
				color:#fff;
			}
			.name {
				font-size: 16px;
				margin-bottom: 5px;
			}
			.bt {
				display: flex;
				justify-content: space-between;
				align-items: center;
				.text {
					width: 0;
					flex: 1;
					padding-right: 5px;
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
					font-size: 12px;
					color: #aaa;
				}
				.time {
					font-size: 12px;
				}
			}
		}
	}
	.right {
		display: flex;
		flex-direction: column;
		height: 100%;
		flex: 1;
		width: 0;
		.msg-box {
			height: 0;
			flex: 1;
			overflow-y: auto;
			padding: 10px;
			.msg-item {
				position: relative;
				padding-left: 45px;
				&:not(:last-child) {
					margin-bottom: 20px;
				}
				&.me {
					padding-left: 0;
					padding-right: 45px;
					.user-img {
						left: auto;
						right: 0;
						background: #6EE7B7;
					}
					.msg-group {
						float: right;
					}
					.name, .time {
						text-align: right;
					}
				}
				.user-img {
					position: absolute;
					top: 0;
					left: 0;
					width: 35px;
					height: 35px;
					line-height: 35px;
					text-align: center;
					border-radius: 50%;
					color: #fff;
					font-size: 12px;
					background: #60A5FA;
				}
				.name {
					padding: 0 10px;
					font-size: 12px;
					color: #aaa;
				}
				.msg-group {
					margin: 5px 0;
					display: inline-block;
					min-width: 100px;
					background: #fff;
					padding: 10px;
					border-radius: 6px;
					float: left;
				}
				.time {
					display: block;
					clear: both;
					padding: 0 10px;
					font-size: 12px;
					color: #aaa;
				}
			}
		}
		.handle-box {
			border-top: 1px solid #d7d7d7;
			min-height: 200px;
			display: flex;
			flex-direction: column;
			.send-choice {
				height: 35px;
				padding: 0 20px;
				display: flex;
				align-items: center;
				gap: 15px;
				border-bottom: 1px solid #d7d7d7;
				font-size: 20px;
				.icon {
					cursor: pointer;
					&:hover {
						color: var(--blue-color);
					}
				}
			}
			.ipt-box {
				height: 0;
				flex: 1;
				.ipt {
					height: 100%;
					:deep(textarea) {
						height: 100%;
					}
				}
			}
			.btn-box {
				display: flex;
				justify-content: space-between;
				align-items: center;
				height: 41px;
				border-top: 1px solid #d7d7d7;
				padding: 0 20px;
			}
		}
	}
}
</style>